package paim.wingchun.controller.eventos;

import java.lang.ref.WeakReference;

import javax.swing.SwingUtilities;

import paim.wingchun.controller.AbstractController;
import paim.wingchun.controller.AbstractSimpleController;
import paim.wingchun.controller.AbstractUniqueController;
import paim.wingchun.view.AbstractSimpleView;
import paim.wingchun.view.AbstractUniqueView;
import paim.wingchun.view.AbstractView;
import paim.wingchun.view.componentes.panel.JPanelButtons;
import paim.wingchun.view.componentes.panel.PanelButtonsListener;

/**
 * @author paim 28/03/2011
 */
public class DefaultPanelButtonsEvent implements PanelButtonsListener {



    WeakReference<? extends AbstractController<?, ?>> controladorReference;

    private WeakReference<JPanelButtons> panelButtonsReference;

    public DefaultPanelButtonsEvent(AbstractController<?, ?> controlador) {

        this.controladorReference = new WeakReference<AbstractController<?, ?>>(controlador);

        if ( controlador instanceof AbstractSimpleController ) {
            JPanelButtons jButtons = ((AbstractSimpleView<?>) controlador.getVisao()).getjPanelBotoes();
            this.panelButtonsReference = new WeakReference<JPanelButtons>(jButtons);
        }
        else if ( controlador instanceof AbstractUniqueController ) {
            JPanelButtons jButtons = ((AbstractUniqueView<?>) controlador.getVisao()).getjPanelBotoes();
            this.panelButtonsReference = new WeakReference<JPanelButtons>(jButtons);

        }
    }


    @Override
    public void confirmar() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AbstractView.Estado confirmado = controladorReference.get().confirmar();

                if ( AbstractView.Estado.Confirmado.equals(confirmado)
                        && controladorReference.get().getPai() != null
                        && controladorReference.get().isConfirmarFechaFilho() ) {
                    controladorReference.get().getVisao().fechar();
                }
            }
        });
    }

    @Override
    public void cancelar() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                boolean cancelado = controladorReference.get().cancelar();

                if ( cancelado && controladorReference.get().getPai() != null
                        && controladorReference.get().isCancelarFechaFilho() )
                    controladorReference.get().getVisao().fechar();
            }
        });
    }

    @Override
    public void fechar() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                controladorReference.get().getVisao().fechar();
            }
        });

    }

    @Override
    public void ajudar() {
        // controladorReference.get()....
        // TODO Auto-generated method stub

    }

}
